package org.hadoop.hive.Utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;
import java.util.Date;
import java.util.Map;

import static io.jsonwebtoken.SignatureAlgorithm.HS256;

public class JwtUtil {
//JWt令牌工具
    private static final String SECRET_KEY = "+yoursecretkey";
    private static final long EXPIRATION_TIME = 3600000; // 1 hour in milliseconds
    public static String genToken(Map<String, Object> subjects) {
        byte[] apiKeySecretBytes = Base64.getDecoder().decode(SECRET_KEY);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, HS256.getJcaName());
        Date expirationDate = new Date(System.currentTimeMillis() + EXPIRATION_TIME);
        String jwtToken = Jwts.builder()
                .setExpiration(expirationDate)
                .claim("subjects", subjects)
                .signWith(HS256, signingKey)
                .compact();

        return jwtToken;
    }

    public static boolean JudgeToken(String token) {
        try {
            Jwts.parser().setSigningKey(Base64.getDecoder().decode(SECRET_KEY)).parseClaimsJws(token);
            return true;
        } catch (io.jsonwebtoken.SignatureException e) {
            return false;
        }
    }

    public static Map<String, Object> praseToken(String token) {
        byte[] apiKeySecretBytes = Base64.getDecoder().decode(SECRET_KEY);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, HS256.getJcaName());

        Claims claims = Jwts.parser()
                .setSigningKey(signingKey)
                .parseClaimsJws(token)
                .getBody();

        return claims;
    }
}
